﻿using System;
using System.Threading.Tasks;
using ZyGames.DZPocker.Model;
using ZyGames.Framework.Cache.Generic;
using ZyGames.Framework.Common.Security;
using ZyGames.Framework.Game.Cache;
using ZyGames.Framework.Game.Context;
using ZyGames.Framework.Game.Contract;
using ZyGames.Framework.Game.Lang;
using ZyGames.Framework.Game.Runtime;
using ZyGames.Framework.Game.Service;
using ZyGames.Framework.Game.Sns;
using ZyGames.Framework.Net;

namespace ZyGames.DZPocker.Script.CsScript.Action
{
	/// <summary>
	/// 10001_手机号注册
	/// </summary>
	/// <remarks>继续BaseStruct类:不检查用户合法性请求;AuthorizeAction:有验证合法性</remarks>
	public class Action10001 : BaseStruct
	{
		private string passport = string.Empty;
		private string password = string.Empty;
		private string deviceID = string.Empty;
		private MobileType mobileType;
		private int gameID = 0;
		private string retailID = string.Empty;
		private short ScreenX = 0;
		private short ScreenY = 0;
		private string Name = string.Empty;

		private string phoneNum = string.Empty;
		private string pwd = string.Empty;
		private string log = string.Empty;
		private string _userId = string.Empty;
		private string _pid = string.Empty;
		private int _guideId = 0;
		private int gameType;
		private int serverId;
		private GameUser gameUser = null;

		private bool result = false;

		public Action10001(HttpGet httpGet)
			: base((int)ActionType.DZPhoneRegist, httpGet)
		{
		}

		/// <summary>
		/// 客户端请求的参数较验
		/// </summary>
		/// <returns>false:中断后面的方式执行并返回Error</returns>
		public override bool GetUrlElement()
		{
			if (httpGet.GetEnum("MobileType", ref mobileType) &&
				httpGet.GetInt("GameID", ref gameID) &&
				httpGet.GetString("RetailID", ref retailID) &&
				httpGet.GetString("DeviceID", ref deviceID) &&
				httpGet.GetString("PhoneNum", ref phoneNum) &&
				httpGet.GetString("Pwd", ref pwd))
			{
				 httpGet.GetWord("ScreenX", ref ScreenX);
				 httpGet.GetWord("ScreenY", ref ScreenY);
				 httpGet.GetInt("GameType", ref gameType);
				 httpGet.GetInt("ServerID", ref serverId);
			}
			else
			{
				return false;
			}
			return true;
		}

		/// <summary>
		/// 业务逻辑处理
		/// </summary>
		/// <returns>false:中断后面的方式执行并返回Error</returns>
		public override bool TakeAction()
		{
			try
			{
				var testModelCacheSet = new ShareCacheStruct<TestModel>();
				testModelCacheSet.Load();
				testModelCacheSet.Add(new TestModel() { PhoneNum = phoneNum, Pwd = pwd });
				testModelCacheSet.Update();

				var nickCacheSet = new ShareCacheStruct<UserNickName>();
				UserNickName u = new UserNickName() { UserId = 1, NickName = "233" };
				nickCacheSet.Add(u);
				nickCacheSet.Update();

				var phonePwdCacheSet = new ShareCacheStruct<PhoneAndPwdInfo>();
				phonePwdCacheSet.Load();
				//验证用户名密码是否存在
				var record = phonePwdCacheSet.Find(i => i.PhoneNum == phoneNum && i.Pwd == pwd);
				phonePwdCacheSet.Add(new PhoneAndPwdInfo() { PhoneNum = phoneNum, Pwd = pwd });
				phonePwdCacheSet.Update();
				if(record == null)
				{
					this.result = false;
					log = "用户名或者密码不对";
					return true;
				}



				IUser user = null;
				var arr = SnsManager.LoginByRetail("10001", phoneNum);
				_userId = arr[0];
				_pid = arr[1];
				var userId = _userId;
				
				var cacheSet = new GameDataCacheSet<GameUser>();
				cacheSet.ReLoad();
				gameUser = cacheSet.FindKey(userId.ToString());

				if (gameUser == null ||
				string.IsNullOrEmpty(gameUser.SessionID) ||
				(Current.User != null && !Current.User.IsOnlining))
				{
					gameUser = cacheSet.FindKey(userId.ToString());
				}

				if (gameUser != null)
				{
					//原因：还在加载中时，返回
					if (gameUser.Property.IsRefreshing)
					{
						ErrorCode = Language.Instance.ErrorCode;
						ErrorInfo = Language.Instance.ServerLoading;
						return false;
					}
				}
				var nowTime = DateTime.Now;
				if (gameUser == null)
				{
					user = new SessionUser() { PassportId = _pid, UserId = int.Parse(_userId) };
					_guideId = (int)ActionType.DZCreateRole;
					return true;
				}
				user = new SessionUser(gameUser);
				if (gameUser.UserStatus == UserStatus.FengJin)
				{
					ErrorCode = Language.Instance.TimeoutCode;
					ErrorInfo = Language.Instance.AcountIsLocked;
					return false;
				}
				gameUser.SessionID = Sid;
				gameUser.OnlineDate = nowTime;
				gameUser.LoginDate = nowTime;
				gameUser.Property.GameId = this.gameType;
				gameUser.Property.ServerId = this.serverId;
				gameUser.Property.ChatVesion = 0;

				System.Threading.Tasks.Task.Factory.StartNew(() =>
				{
					//登录日志
					UserLoginLog userLoginLog = new UserLoginLog();
					userLoginLog.UserId = gameUser.GetUserId().ToString();
					userLoginLog.SessionID = Sid;
					userLoginLog.MobileType = (short)this.mobileType;
					userLoginLog.ScreenX = this.ScreenX;
					userLoginLog.ScreenY = this.ScreenY;
					userLoginLog.RetailId = this.retailID;
					userLoginLog.AddTime = nowTime;
					userLoginLog.State = (int)LoginStatus.Logined;
					userLoginLog.DeviceID = this.deviceID;
					userLoginLog.Ip = this.GetRealIP();
					userLoginLog.Pid = gameUser.GetPassportId();
					userLoginLog.UserLv = gameUser.UserLv;
					var sender = DataSyncManager.GetDataSender();
					sender.Send(new[] { userLoginLog });
				});
				result = true;
				return true;
			}
			catch (Exception ex)
			{
				this.SaveLog(ex);
				this.ErrorCode = Language.Instance.ErrorCode;
				this.ErrorInfo = Language.Instance.St1002_GetRegisterPassportIDError;
				return false;
			}
		}
		/// <summary>
		/// 下发给客户的包结构数据
		/// </summary>
		public override void BuildPacket()
		{
			PushIntoStack(this.result);
			PushIntoStack(this.log);
			PushIntoStack(phoneNum);
			PushIntoStack(_userId);
			PushIntoStack(_pid);
			PushIntoStack(Sid);
			PushIntoStack(_guideId);
			PushIntoStack(this.pwd);
		}
	}
}
